package com.lock.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Component
public class RedisLockUtil {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取分布式锁（SETNX）
     */
    public boolean tryLock(String key, String value, long expireTime, TimeUnit timeUnit) {
        return Boolean.TRUE.equals(redisTemplate.opsForValue()
                .setIfAbsent(key, value, expireTime, timeUnit));
    }

    /**
     * 释放锁（Lua脚本保证原子性）
     */
    public boolean releaseLock(String key, String value) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = RedisScript.of(script, Long.class);
        return redisTemplate.execute(redisScript, Collections.singletonList(key), value) == 1;
    }
}
